/**
 * Copyright (c) 2012-2017, www.tinygroup.org (luo_guo@icloud.com).
 * <p>
 *  Licensed under the GPL, Version 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * <p>
 *       http://www.gnu.org/licenses/gpl.html
 * <p>
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.tinygroup.cepcore.impl;

import java.util.ArrayList;
import java.util.List;

import org.tinygroup.cepcore.CEPCore;
import org.tinygroup.cepcore.CEPCoreProcessFilter;
import org.tinygroup.cepcore.CEPCoreProcessFilterChain;
import org.tinygroup.cepcore.EventProcessor;
import org.tinygroup.commons.tools.CollectionUtil;
import org.tinygroup.event.Event;

public class CEPCoreProcessFilterChainImpl implements CEPCoreProcessFilterChain {
	List<CEPCoreProcessFilter> filters = new ArrayList<CEPCoreProcessFilter>();
//	boolean filtersSetTag = false;
	
	public CEPCoreProcessFilterChainImpl(List<CEPCoreProcessFilter> filters) {
		setFilters(filters);
	}

	public void process(Event e, CEPCore core, EventProcessor processor) {
		if (CollectionUtil.isEmpty(filters)) {
			return;
		}
		filters.get(0).process(e, core, processor);
	}

	public void addFilter(CEPCoreProcessFilter filter) {
		if (CollectionUtil.isEmpty(filters)) {
			filters.add(filter);
			return;
		}
		if(filters.size()==1){ //最后一位固定
			insertFilterToBegin(filter);
			return;
		}
		//设置倒数第二指向当前
		filters.get(filters.size() - 2).setNext(filter);
		//设置当前指向倒数第一
		filter.setNext(filters.get(filters.size()-1));
		//设置当前为倒数第二
		filters.add(filters.size() - 1,filter);
	}

	public void insertFilterToBegin(CEPCoreProcessFilter filter) {
		if (CollectionUtil.isEmpty(filters)) {
			filters.add(filter);
			return;
		}
		//设置当前指向第一位
		filter.setNext(filters.get(0) );
		//设置当前为第一位
		filters.add(0, filter);
	}

	public List<CEPCoreProcessFilter> getFilters() {
		return filters;
	}

	public void setFilters(List<CEPCoreProcessFilter> filters) {
		if (CollectionUtil.isEmpty(filters)) {
			return;
		}
		this.filters = filters;
		for (int i = 0; i < filters.size() - 1; i++) {
			CEPCoreProcessFilter filter = filters.get(i);
			filter.setNext(filters.get(i + 1));
		}
	}

}
